package models

import (
	"errors"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

//查询
type ErpProductsQueryParam struct {
	BaseQueryParam
	Filter        string
	Status        int
	Typeid        int           //类别ID
	Typeids       []int         //类别ID
	NoSetId       []interface{} //不需要的商品ID
	Depids        []string //部门列表
	ClassType     int           //类别类型
	DepartmentId  int64
	Suppliers     int64
	Refractivity  string `json:"refractivity"`
	OpticalDesign string `json:"optical_design"`
	FunctionInfo  string `json:"function_info"`
	Film          string `json:"film"`
}

type ErpProducts struct {
	Id              int64
	DepartmentId    int64
	Number          string
	Suppliers       *ErpSuppliers `orm:"rel(fk);null;on_delete(do_nothing)"`
	Name            string
	FullName        string //产品全称
	Pinyin          string //拼音
	Brand           *ErpBrand `orm:"rel(fk);null;on_delete(do_nothing)"`
	BrandName       string
	TypeId          int //固定类型
	BarCode         string
	Unit            string
	ColourNumber    string //色号
	ModelNumber     string //型号
	Manufacturer    string //生产企业
	RegistrationId  string //注册证号
	Genre           string //镜片类型
	OpticalDesign   string //光学设计
	Refractivity    string //折射率
	FunctionInfo    string //功效
	MaterialQuality string //镜片材质
	Spec            string //隐形规格
	CastAway        string //配戴周期
	ShelfLife       string //保质期
	ProducingArea   string //产地
	Film            string //镜片膜层
	FilmColor       string //镜片膜层颜色
	CreatedAt       int64
	UpdatedAt       int64
	CreatedBy       string
	UpdatedBy       string
	Summary         string
	Status          int
	UpperLimit      int64 //库存上线
	LowerLimit      int64 //库存下线
}

func (a *ErpProducts) TableName() string {
	return ErpProductsTableName()
}

func ErpProductsTableName() string {
	return TableName("erp_products")
}

func GetGetErpProductsQuerySeter() orm.QuerySeter {
	return orm.NewOrm().QueryTable(ErpProductsTableName()).RelatedSel("Suppliers")
}

func GetErpProductsById(id int64, u *BackendUser) (*ErpProducts, error) {

	r := new(ErpProducts)
	err := GetGetErpProductsQuerySeter().Filter("DepartmentId", u.DepartmentId).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func ErpProductsPageList(params *ErpProductsQueryParam) ([]*ErpProducts, int64) {

	ls := make([]*ErpProducts, 0)

	query := GetGetErpProductsQuerySeter()

	cond := orm.NewCondition()
	if len(params.Filter) > 0 { //搜索直接查规格名
		cond = cond.Or("name__contains", params.Filter)
	}

	query = query.SetCond(cond)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	if params.Status != 0 {
		query = query.Filter("status", params.Status)
	}
	if len(params.Typeids) > 0 {
		query = query.Filter("type_id__in", params.Typeids)
	}
	if len(params.NoSetId) > 0 {
		query = query.Exclude("id__in", params.NoSetId)
	}
	if params.Typeid > 0 {
		query = query.Filter("type_id", params.Typeid)
	}

	if params.Suppliers > 0 {
		query = query.Filter("suppliers_id", params.Suppliers)
	}

	if params.DepartmentId > 0 {
		query = query.Filter("DepartmentId", params.DepartmentId)
	}

	if len(params.Depids) > 0 {
		query = query.Filter("DepartmentId__in", params.Depids)
	}
	if len(params.Refractivity) > 0 {
		query = query.Filter("Refractivity", params.Refractivity)
	}
	if len(params.OpticalDesign) > 0 {
		query = query.Filter("OpticalDesign", params.OpticalDesign)
	}
	if len(params.FunctionInfo) > 0 {
		query = query.Filter("FunctionInfo", params.FunctionInfo)
	}
	if len(params.Film) > 0 {
		query = query.Filter("FunctionInfo", params.Film)
	}

	total, _ := query.Count()
	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

//添加产品为批量处理
func ErpProductsAdd(c []*ErpProducts) (int64, error) {

	to,_ := orm.NewOrm().Begin()
	qs := GetGetErpProductsQuerySeter()
	i, _ := qs.PrepareInsert()
	number := int64(0)
	for _, da := range c {
		_, err := i.Insert(da)
		if err == nil {
			number++
		} else {
			to.Rollback()
			return 0, err
		}
	}
	to.Commit()
	return number, nil
}

func (a *ErpProducts) ErpProductsEdit(filter ...string) error {

	a.UpdatedAt = time.Now().Unix()

	if _, err := orm.NewOrm().Update(a, filter...); err != nil {
		return err
	}
	return nil
}

func ErpProductsDel(id, depid int64) error {

	var c ErpProducts
	c = ErpProducts{Id: id, Status: 2}

	orm.NewOrm().Read(&c)
	if c.Status == 1 {
		c.Status = 2
	} else {
		c.Status = 1
	}
	if c.DepartmentId != depid {
		return errors.New("数据不存在")
	}

	if err := c.ErpProductsEdit("status"); err != nil {
		return err
	}
	return nil
}

func ProductGroupName(data *ErpProducts) string {
	var name string
	var gName string
	if (data.BrandName != data.Name) {
		gName = data.BrandName + data.Name;
	} else {
		gName = data.Name;
	}
	switch (data.TypeId) {
	case 10:
		name = gName + data.Refractivity + data.Genre + data.OpticalDesign + data.FunctionInfo;
		break;
	case 20:
		name = gName + data.CastAway + data.Spec + data.ColourNumber;
		break;
	case 30:
		name = gName + data.MaterialQuality;
		break;
	case 40:
		name = gName + data.ModelNumber + data.ColourNumber + data.Genre;
		break;
	case 41:
		name = gName;
		break;
	case 50:
		name = gName + data.Spec;
		break;
	default:
		name = gName;
		break;
	}
	return name;
}
